<template>
  <div>
    <div class="search-wrap d-flex a-center flex-wrap">
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>账套名称</label>
        <el-select class="m-l10" v-model="form.projectSetBelongId" clearable>
          <el-option
            v-for="(item, index) in projectSetBelong"
            :key="index"
            :label="item.projectSetBelongName"
            :value="item.projectSetBelongId"
          ></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>年度</label>
        <el-date-picker
          :clearable="false"
          class="m-l10"
          v-model="form.year"
          value-format="YYYY"
          size="large"
          type="year"
          placeholder="请选择"
        />
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>季度</label>
        <el-select class="m-l10" v-model="form.quarter" clearable>
          <el-option label="第一季度" value="1"></el-option>
          <el-option label="第二季度" value="2"></el-option>
          <el-option label="第三季度" value="3"></el-option>
          <el-option label="第四季度" value="4"></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>月度</label>
        <el-select class="m-l10" v-model="form.monthly" clearable>
          <el-option
            v-for="i in 12"
            :key="i"
            :label="i + `月`"
            :value="i"
          ></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>计划类型</label>
        <el-select class="m-l10" v-model="form.planType">
          <el-option label="计划内" value="1"></el-option>
          <el-option label="计划外" value="2"></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label class="m-r5">项目集</label>
        <el-cascader
          v-model="form.projectSetIdVal"
          :options="options"
          :props="props"
          clearable
          @change="cascaderChange"
          :show-all-levels="false"
        ></el-cascader>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>审核状态</label>
        <el-select class="m-l10" v-model="form.status" clearable>
          <el-option label="未提交" value="0"></el-option>
          <el-option label="审核中" value="1"></el-option>
          <el-option label="审核成功" value="2"></el-option>
          <el-option label="审核失败" value="3"></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <el-button color="#fc702b" style="color: #fff" @click.prevent="onQuery"
          >查询</el-button
        >
        <el-button
          color="#f0f0f0"
          style="color: #000000"
          @click.prevent="onReset"
          >重置</el-button
        >
      </div>
      <el-divider direction="vertical" class="m-b10" />
      <div class="search-buttons m-b10">
        <el-button class="button_edit" @click="onExport2">
          <svg-icon
            icon-class="project-detail-icon-derive"
            class="icon-export m-r5"
          ></svg-icon>
          流入流出数据导出
        </el-button>
        <el-button class="button_edit" @click="onExport">
          <svg-icon
            icon-class="project-detail-icon-derive"
            class="icon-export m-r5"
          ></svg-icon>
          导出预算明细
        </el-button>
        <el-button class="button_edit" @click="initiateProcess">
          发起流程
        </el-button>
      </div>
    </div>
    <!--    disabledSelectAll-->
    <public-table
      ref="publicTableRef"
      class="m-t20"
      index
      border
      selection
      height="550"
      :page="page"
      :tableData="tableData"
      :cell-style="{ background: 'revert' }"
      :tableOption.sync="tableOption"
      :objectSpanMethod="objectSpanMethod"
      @page-change="onPageChange"
      @handleSelectionChange="handleSelectionChange"
      @selectClick="handleSelectSingle"
    >
      <template #subjectName="scope">
        <el-cascader
          style="width: 100px"
          v-if="scope.row.isEdit"
          clearable
          v-model="scope.row.subjectId"
          :props="props2"
        />
        <span class="m-l5">{{ scope.row.subjectName }}</span>
      </template>
      <template #budgetAmount="scope">
        <span v-if="!scope.row.isEdit">{{ scope.row.budgetAmount }}</span>
        <el-input
          v-else
          v-model="scope.row.budgetAmount"
          placeholder="请输入预算金额"
          @input="
            scope.row.budgetAmount = limitInputNum(
              scope.row.budgetAmount,
              13,
              3,
              true
            )
          "
        ></el-input>
      </template>

      <template #moneyFlow="{ row }">
        <span>{{ row.moneyFlow == 1 ? "流入" : "流出" }}</span>
      </template>
      <template #status="scope">
        <span v-if="scope.row.status == 0" style="color: #aaaaaa">{{
          status[scope.row.status]
        }}</span>
        <span v-if="scope.row.status == 1" style="color: #f59a23">{{
          status[scope.row.status]
        }}</span>
        <span v-if="scope.row.status == 2" style="color: #70b603">{{
          status[scope.row.status]
        }}</span>
        <span v-if="scope.row.status == 3" style="color: #a30014">{{
          status[scope.row.status]
        }}</span>
      </template>

      <template #remarks="scope">
        <el-input
          v-if="scope.row.isEdit"
          v-model="scope.row.remarks"
          placeholder="请输入备注"
        ></el-input>
        <span v-else>{{ scope.row.remarks }}</span>
      </template>
      <template #update="scope">
        <el-button
          size="mini"
          v-if="isShow(scope.row.status, '编辑')"
          type="primary"
          class="button_edit"
          @click="handleEdit(scope.row)"
          >编辑</el-button
        >
        <el-button
          v-if="scope.row.isEdit"
          color="#fff8f6"
          style="
            color: #fc7037;
            border-color: #fc7037;
            background-color: #fff8f6;
          "
          @click="onSave(scope.row)"
          >保存</el-button
        >
        <el-button
          v-if="isShow(scope.row.status, '删除')"
          size="mini"
          type="danger"
          class="button_delete"
          @click="handleDelete(scope.row)"
          >删除</el-button
        >
        <el-button
          size="mini"
          type="success"
          class="button_view"
          @click="controlToProject(scope.row)"
        >
          管控至项目
        </el-button>
      </template>
    </public-table>

    <control-to-project-popup
      ref="controlToProjectPopupRef"
      @on-success="onSuccess"
    />
  </div>
</template>

<script setup>
import {
  ElDatePicker,
  ElDivider,
  ElOption,
  ElSelect,
  ElCascader,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import { onMounted, reactive, ref, nextTick } from "vue";
import { projectApi } from "@/api/project";
import {
  budgetManagement,
  exportApi,
  fundManagementApi,
} from "@/api/businessFinance";
import PublicTable from "@/components/PublicTable.vue";
import {
  exportExcelFile,
  getURLhandler,
  limitInputNum,
} from "@/common/utils/GlobalUtils";
import ControlToProjectPopup from "@/views/businessFinance/fundManagement/fundBudgetManagement/components/controlToProjectPopup.vue";
import { useRoute } from "vue-router";

const route = useRoute();
const year = getURLhandler(route.path).id;
const projectSetBelongId = getURLhandler(route.path).projectSetBelongId;
const departmentId = getURLhandler(route.path).departmentId;

const form = reactive({
  departmentId: "",
  projectSetId: "",
  year: "",
  monthly: "",
  projectSetBelongId: "",
  type: "",
  quarter: "",
  projectSetIdVal: "",
  status: "",
  planType: "1",
});

const options = ref([]);
const props = reactive({
  value: "projectSetId",
  label: "projectSetName",
  children: "child",
});

/**
 * 获取当前年份
 */
const getYear = () => {
  return new Date().getFullYear().toString();
};

/**
 * 项目集级联选择器
 */
const cascaderChange = (e) => {
  if (e && e.length) {
    form.projectSetId = e[e.length - 1];
  }
  if (!e) {
    form.projectSetId = "";
  }
};

/**
 * 查询项目集树形结构
 */
const getProjectSetListTree = () => {
  projectApi.getProjectSetListTree({}).then((res) => {
    options.value = res.data;
  });
};

/**
 * 预算明细导出
 */
const onExport = () => {
  /* exportApi.fundBudgetPlanSetLeadingOut(form).then(res=>{
          if(res){
              exportExcelFile(res,'预算明细');
          }
      });*/

  exportApi.getDepartmentBudgetPlanLeadingOutInfo(form).then((res) => {
    if (res) {
      exportExcelFile(res, "预算明细");
    }
  });
};

/**
 * 流入流出导出
 */
const onExport2 = () => {
  exportApi.getDepartmentSummarySubLeadingOut(form).then((res) => {
    if (res) {
      exportExcelFile(res, "流入流出");
    }
  });
};

/**
 * 筛选排序
 */
const filter = (arr, filed) => {
  let temObj = {};
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (!temObj[item[filed]]) {
      temObj[item[filed]] = [item];
    } else {
      temObj[item[filed]].push(item);
    }
  }
  let resArr = [];
  Object.keys(temObj).forEach((key) => {
    resArr.push({
      key: key,
      data: temObj[key],
    });
  });
  return resArr;
};

/**
 * 资金预算台账
 */
const getDepartmentBudgetPlanDetail = (params) => {
  const { param, ...rest } = params;
  fundManagementApi
    .getDepartmentBudgetPlanDetail({
      param: { ...param, departmentId },
      ...rest,
    })
    .then((res) => {
      if (res.code === "200") {
        let data = [];
        res.data.content.forEach((item, index) => {
          item.list.forEach((val) => {
            data.push({
              ...item,
              ...val,
              index,
              isEdit: false,
            });
          });
        });
        let arr = filter(data, "firstMainProjectName");
        let tempArr = [];
        for (let key in arr) {
          let obj = arr[key];
          tempArr.push(...obj.data);
        }

        console.log(tableData.value);
        tableData.value = tempArr;
        page.total = res.data.totalSize;
      }
    });
};

/**
 *
 */
const onQuery = () => {
  page.current = 1;
  page.size = 10;
  getDepartmentBudgetPlanDetail({
    pageNum: page.current,
    pageSize: page.size,
    param: form,
  });
};

/**
 *
 */
const onReset = () => {
  form.departmentId = "";
  form.projectSetId = "";
  form.year = getYear();
  form.monthly = "";
  form.projectSetBelongId = "";
  form.type = "";
  form.quarter = "";
  form.projectSetIdVal = "";
  form.status = "";
  form.planType = "1";
  page.current = 1;
  page.size = 10;
  getDepartmentBudgetPlanDetail({ pageNum: 1, pageSize: 10, param: form });
};

const page = reactive({
  total: 0,
  current: 1,
  size: 10,
});

const tableData = ref([]);

const status = ref({
  0: "未审核",
  1: "审核中",
  2: "审核成功",
  3: "审核失败",
});
const tableOption = ref([
  {
    label: "账套名称",
    prop: "projectSetBelongName",
    minWidth: 80,
    align: "center",
  },
  {
    label: "项目集 ",
    prop: "firstMainProjectName",
    minWidth: 80,
    align: "center",
  },
  { label: "项目子集 ", prop: "projectSetName", minWidth: 80, align: "center" },
  { label: "年度", prop: "year", minWidth: 80, align: "center" },
  { label: "季度", prop: "quarter", minWidth: 80, align: "center" },
  { label: "月度", prop: "monthly", minWidth: 80, align: "center" },
  {
    label: "性质",
    prop: "moneyFlow",
    minWidth: 80,
    slot: true,
    align: "center",
  },
  {
    label: "资金计划科目",
    prop: "subjectName",
    minWidth: 150,
    slot: true,
    align: "center",
  },
  {
    label: "资金计划金额",
    prop: "budgetAmount",
    minWidth: 80,
    slot: true,
    align: "center",
  },
  {
    label: "审核状态",
    prop: "status",
    minWidth: 80,
    slot: true,

    align: "center",
  },
  { label: "备注", prop: "remarks", minWidth: 80, align: "center", slot: true },
  { label: "操作", prop: "update", minWidth: 280, slot: true, align: "center" },
]);

// 合并表格
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  let data = tableData.value; //拿到当前table中数据
  let cellValue = row[column.property]; //当前位置的值
  if (columnIndex == 1 || columnIndex == 2 || columnIndex == 3) {
    let prevRow = data[rowIndex - 1]; //获取到上一条数据
    let nextRow = data[rowIndex + 1]; //下一条数据

    if (prevRow && prevRow[column.property] === cellValue) {
      //当有上一条数据，并且和当前值相等时
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.property] === cellValue) {
        //当有下一条数据并且和当前值相等时,获取新的下一条
        nextRow = data[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  } else if (columnIndex == 0) {
    let prevRow = data[rowIndex - 1]; //获取到上一条数据
    let nextRow = data[rowIndex + 1]; //下一条数据

    if (prevRow && prevRow.index == row.index) {
      //当有上一条数据，并且和当前值相等时
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow.index == row.index) {
        //当有下一条数据并且和当前值相等时,获取新的下一条
        nextRow = data[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
};

const onPageChange = (e) => {
  page.current = e.page;
  page.size = e.limit;
  let param = {
    param: {
      ...form,
    },
    pageNum: page.current,
    pageSize: page.size,
  };
  getDepartmentBudgetPlanDetail(param);
};

const projectSetBelong = ref([]);
/**
 * 获取项目集归属
 */
const getProjectSetBelong = () => {
  projectApi.getProjectSetBelong().then((res) => {
    if (res.code === "200") {
      projectSetBelong.value = res.data;
    }
  });
};

function uniqueArr(arr) {
  let result = [];
  arr.forEach((item) => {
    if (!result.some((m) => m.index === item.index)) {
      result.push(item);
    }
  });
  return result;
}

const selectList = ref([]);
const handleSelectionChange = (e) => {
  selectList.value = uniqueArr(e);
};

const publicTableRef = ref();
const handleSelectSingle = (row) => {
  const selectArr = [...selectList.value];
  const curIsSelect = selectArr.findIndex((item) => item.index == row.index);

  if (curIsSelect < 0) {
    selectArr.push(row);
  } else {
    selectArr.splice(curIsSelect, 1);
  }
  toggleSelection(selectArr, true);
};

// 默认选择/取消中的行
function toggleSelection(rows, bool) {
  if (rows) {
    nextTick(() => {
      publicTableRef.value?.clearSelection();
      rows.forEach((row) => {
        publicTableRef.value?.toggleRowSelection(row, bool);
      });
    });
  } else {
    publicTableRef.value?.clearSelection();
  }
}

/**
 * 发起流程
 */
const initiateProcess = () => {
  if (!selectList.value.length) {
    return ElMessage.warning("请选择数据!");
  }
  console.log(selectList.value);

  fundManagementApi.initiateBudgetProcess(selectList.value).then((res) => {
    if (res.code === "200") {
      ElMessage.success("发起流程成功!");
      selectList.value = [];
      onQuery();
    }
  });
};

/**
 * 管控至项目成功
 */
const onSuccess = () => {
  onQuery();
};

/**
 * 编辑
 * @param row
 */
const handleEdit = (row) => {
  row.isEdit = true;
};

/**
 * 是否显示操作按钮
 * @param status
 * @param buttonName
 */
const isShow = (status, buttonName) => {
  if (status === 1) {
    return false;
  }
  if (
    (status === 0 && buttonName === "删除") ||
    (status === 0 && buttonName === "编辑")
  ) {
    return true;
  }
  if (status === 2 && buttonName === "调整") {
    return true;
  }
  if (
    (status === 3 && buttonName === "删除") ||
    (status === 3 && buttonName === "编辑")
  ) {
    return true;
  }
  return false;
};

/**
 * 删除
 * @param row
 */
const handleDelete = (row) => {
  ElMessageBox.alert("确认删除吗?", "提示", {
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    callback: (action) => {
      if (action === "confirm") {
        budgetManagement.deleteBudget(row.budgetPlanId).then((res) => {
          ElMessage.success("删除成功!");
          onQuery();
        });
      }
    },
  });
};

const props2 = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level } = node;
    if (level === 0) {
      const res = await fundManagementApi.getBudgetSubjectList({
        subjectId: "",
        subjectType: "1",
      });
      let nodes = [];
      res.data.forEach((item) => {
        nodes.push({
          value: item.subjectId,
          label: item.subjectName,
          leaf: level >= 4,
        });
      });
      resolve(nodes);
    }
    if (level > 0 && level === 5) {
      resolve([]);
    }
    if (level > 0 && level < 5) {
      const res = await fundManagementApi.getBudgetSubjectList({
        subjectId: node.value,
        subjectType: "1",
      });
      let nodes = [];
      res.data.forEach((item) => {
        nodes.push({
          value: item.subjectId,
          label: item.subjectName,
          leaf: level >= 4,
        });
      });
      resolve(nodes);
    }
  },
};

const controlToProjectPopupRef = ref(null);

/**
 * 管控至项目
 * @param row
 */
const controlToProject = (row) => {
  controlToProjectPopupRef.value.openPopup(row.budgetPlanId);
};

/**
 * 保存
 * @param row
 */
const onSave = (row) => {
  if (row.budgetAmount === "") {
    ElMessage.warning("请输入预算金额!");
    return;
  }
  budgetManagement
    .updateBudget({
      budgetPlanId: row.budgetPlanId,
      subjectId: Array.isArray(row.subjectId)
        ? row.subjectId[row.subjectId.length - 1]
        : row.subjectId,
      budgetAmount: row.budgetAmount,
      remarks: row.remarks,
    })
    .then((res) => {
      if (res.code === "200") {
        row.isEdit = false;
        ElMessage.success("编辑成功");
        onQuery();
      }
    });
};

onMounted(() => {
  getProjectSetListTree();
  form.year = year || "";
  form.projectSetBelongId = projectSetBelongId || "";
  getDepartmentBudgetPlanDetail({ pageNum: 1, pageSize: 10, param: form });
  getProjectSetBelong();
});
</script>

<style lang="scss" scoped></style>
